package com.aerotechnic.dao.implementation;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.aerotechnic.dao.interfaces.JobcardDaoIn;
import com.aerotechnic.entities.JobCard;

@Repository("JobCardDao")
public class JobCardDao implements JobcardDaoIn {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(JobCard t) {

		// TODO Auto-generated method stub

		getCurrentSession().saveOrUpdate(t);

	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub

		JobCard e = findByID(id);
		if (e != null)
			getCurrentSession().delete(e);

	}

	@Override
	public JobCard findByID(Long id) {
		// TODO Auto-generated method stub

		Session session = sessionFactory.getCurrentSession();

		return (JobCard) session.createQuery("FROM JobCard where id= " + id)
				.list().get(0);
	}

	@Override
	public void update(JobCard t) {
		// TODO Auto-generated method stub

		getCurrentSession().update(t);
	}

	public List<JobCard> findAll() {
		// TODO Auto-generated method stub

		return getCurrentSession().createQuery("from JobCard").list();
	}

	@Override
	public JobCard findByNumero(Long num) {
		// TODO Auto-generated method stub
		List<JobCard> jobCards = getCurrentSession().createQuery(
				"from JobCard where numero = " + num).list();

		return jobCards.isEmpty() ? null : jobCards.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<JobCard> findByVisiteId(Long visiteId) {
		// TODO Auto-generated method stub
		return getCurrentSession().createQuery(
				"from JobCard where visiteId = " + visiteId).list();
	}

	@Override
	public List<JobCard> findUnstuckJBByVisiteId(Long visiteId) {
		// TODO Auto-generated method stub
		return getCurrentSession().createQuery(
				"from JobCard where isStuck=false and  visiteId = " + visiteId).list();
	}

}
